<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查询</el-button>
      <el-button v-if="canPublishApp" class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-plus" @click="handleAdd">发布程序</el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      border
      fit
      :height="tableHeight"
      :data="list"
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
      @selection-change="selsChange"
    >
      <el-table-column type="index" width="60" />
      <el-table-column prop="appName" label="应用" width="220" :formatter="formatAppName" />
      <el-table-column prop="packageType" label="程序包类型" width="120" />
      <el-table-column prop="versionName" label="版本" width="100" />
      <el-table-column prop="versionCode" label="版本值" width="80" />
      <el-table-column prop="latest" label="最新版" width="100" :formatter="formatLatest" />
      <el-table-column prop="uploadTime" label="上传时间" width="160" />
      <el-table-column label="操作" min-width="120" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="small" @click="handlePackageItem(scope.index, scope.row)">文件列表</el-button>
          <el-button size="small" @click="handleSetLatest(scope.index, scope.row)">设置为最新版</el-button>
          <el-button size="small" :loading="scope.row.loading" @click="handleDownloadZip(scope.index, scope.row)">下载程序包</el-button>
          <el-button size="small" @click="handleDownloadQrCode(scope.index, scope.row)">程序包二维码</el-button>
          <el-button size="small" @click="handleDeletePackage(scope.index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="filters.page" :limit.sync="filters.limit" @pagination="loadPageList" />

    <!--新增界面-->
    <el-dialog title="应用发布" :visible.sync="addFormVisible" :close-on-click-modal="false">
      <el-form ref="addForm" :model="addForm" :label-width="formLabelWidth" :rules="addFormRules">
        <el-form-item label="名称" prop="name">
          <el-radio-group v-model="addForm.appName">
            <el-radio label="movie-tool" border>剧本配置工具</el-radio>
            <el-radio label="movie-tool-update" border>剧本配置工具更新程序</el-radio>
            <el-radio label="ffplayer" border>剧本播放器</el-radio>
            <el-radio label="ffplayer-update" border>剧本播放器更新程序</el-radio>
            <el-radio label="pad" border>pad端程序</el-radio>
            <el-radio label="players-app">玩家端程序</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="程序包类别" prop="packageType">
          <el-radio-group v-model="addForm.packageType">
            <el-radio label="Windows" border>Windows</el-radio>
            <el-radio label="Android" border>Android</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="版本" prop="versionName">
          <el-input v-model="addForm.versionName" auto-complete="off" />
        </el-form-item>
        <el-form-item v-if="addForm.packageType ==='Android'" label="版本值" prop="versionCode">
          <el-input v-model="addForm.versionCode" auto-complete="off" />
        </el-form-item>
        <el-form-item label="程序包目录" prop="fileList">
          <folder-selector ref="folderSelector" v-model="fileList" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addFormVisible = false">取消</el-button>
        <el-button type="primary" :loading="addLoading" :disabled="submitDisabled" @click="addSubmit">提交</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="appPackageFileTitle" :visible.sync="appPackageFileVisible" :close-on-click-modal="false">
      <el-table
        v-loading="appPackageFileListLoading"
        border
        fit
        :height="360"
        :data="appPackageFileList"
        highlight-current-row
        style="width: 100%;"
      >
        <el-table-column type="index" width="60" />
        <el-table-column prop="relativePath" label="文件" min-width="120" />
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="appPackageFileVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <el-dialog title="程序包下载二维码" :visible.sync="qrCodeVisible" :close-on-click-modal="false">
      <div class="qr-code-container">
        <qrcode :size="156" :text="qrContent" />
        <p>{{ qrInfo.name }}-{{ qrInfo.version }}</p>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="qrCodeVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import FolderSelector from '@/components/folder-selector'
import Pagination from '@/components/Pagination'
import waves from '@/directive/waves'
import sha1 from 'js-sha1'
import {
  appPackageFileItems,
  deleteAppPackage,
  listAppPackages,
  saveAppPackageItem,
  saveAppPackages,
  setAppPackageLatest, uploadFile,
  uploadPackageFiles,
  downloadAppPackage
} from '@/api/app-package'
import util from '@/utils/util.js'
import { mapGetters } from 'vuex'
import Qrcode from '@/components/qrcode'

export default {
  name: 'AppPackages',
  components: { Pagination, FolderSelector, Qrcode },
  directives: { waves },
  data() {
    return {
      tableHeight: 260,
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: false,
      sels: [], // 列表选中列
      filters: {
        page: 1,
        limit: 20
      },
      orderBy: {
        orderColumn: '',
        order: ''
      },
      addFormVisible: false,
      addLoading: false,
      submitDisabled: false,
      addForm: {
        appName: '',
        packageType: '',
        productType: 'Lewin',
        versionName: '',
        versionCode: 0
      },
      addFormRules: {
        versionName: [{ required: true, message: '版本不能为空', trigger: 'blur' }]
      },
      fileList: [],
      fileInfos: [],

      appPackageFileTitle: '',
      appPackageFileVisible: false,
      appPackageFileListLoading: false,
      appPackageFileList: [],

      qrCodeVisible: false,
      qrInfo: {
        name: '',
        version: ''
      },
      qrContent: '{}'
    }
  },
  computed: {
    ...mapGetters(['formLabelWidth', 'userInfo']),
    canPublishApp() {
      const roles = this.userInfo.roles || []
      return roles.indexOf('Admin') !== -1
    }
  },
  watch: {
    fileList: function(n, o) {
      this.fileInfos = []
      this.submitDisabled = true
      for (let i = 0; i < n.length; ++i) {
        this.fileDigest(n[i])
      }
    }
  },
  created() {
    this.tableHeight = window.innerHeight - 200
    this.loadPageList()
  },
  methods: {
    formatLatest(row) {
      if (row.latest === 1) {
        return '是'
      }
      return '否'
    },
    formatAppName(row) {
      if (row.appName === 'movie-tool') {
        return '剧本配置工具'
      } else if (row.appName === 'ffplayer') {
        return '剧本播放器'
      } else if (row.appName === 'movie-tool-update') {
        return '剧本配置工具更新程序'
      } else if (row.appName === 'ffplayer-update') {
        return '剧本播放器更新程序'
      } else if (row.appName === 'pad') {
        return 'pad端程序'
      } else if (row.appName === 'players-app') {
        return '玩家端程序'
      }
      return '未知'
    },
    loadPageList() {
      this.listLoading = true
      const param = { ...this.filters, ...this.orderBy }
      listAppPackages(param).then(({ success, message, data }) => {
        this.listLoading = false
        if (success) {
          const { records, total } = data || {}
          if (records && records.length > 0) {
            for (let i = 0; i < records.length; ++i) {
              records[i].loading = false
            }
          }
          this.list = records
          this.total = total
        } else {
          this.$message({
            message: message || '查询列表失败',
            type: 'error'
          })
        }
      }, () => {
        this.listLoading = false
      })
    },
    handleFilter() {
      this.filters.page = 1
      this.loadPageList()
    },
    sortChange({ prop, order }) {
      this.orderBy.orderColumn = prop
      this.orderBy.order = order
      this.handleFilter()
    },
    selsChange(sels) {
      this.sels = sels
    },
    handleAdd() {
      this.addFormVisible = true
      this.addForm.appName = 'movie-tool'
      this.addForm.packageType = 'Windows'
      this.addForm.productType = 'Lewin'
      this.addForm.versionName = ''
      this.fileList = []
      this.$nextTick(() => {
        this.$refs['addForm'].clearValidate()
      })
    },
    addSubmit() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.addLoading = true
            saveAppPackages(this.addForm).then(({ success, message, data }) => {
              if (success) {
                if (this.fileList && this.fileList.length > 0) {
                  this.uploadAppPackageFiles(data)
                } else {
                  this.addLoading = false
                }
              } else {
                this.$message({
                  message: message || '添加失败',
                  type: 'error'
                })
                this.addLoading = false
              }
            }, () => {
              this.addLoading = false
            })
          })
        }
      })
    },
    fileDigest(file) {
      const thiz = this
      const folder = this.$refs.folderSelector.getFolder()
      const relativePath = file.webkitRelativePath.substring(folder.length + 1)
      const reader = new FileReader()
      reader.readAsArrayBuffer(file)
      reader.onload = function() {
        const digest = sha1(this.result)
        thiz.fileInfos.push({ file, digest, relativePath })
        if (thiz.fileInfos.length === thiz.fileList.length) {
          thiz.submitDisabled = false
        }
      }
    },
    saveAppPackageItem(appPackageId, fileItem) {
      const relativePath = fileItem.relativePath
      const fileName = fileItem.file.name
      const digest = fileItem.digest
      const param = { appPackageId, relativePath, fileName, digest }
      return new Promise((resolve, reject) => {
        saveAppPackageItem(param).then(({ success, message, data }) => {
          if (success) {
            resolve(data)
          } else {
            reject(message)
          }
        }, res => reject(res))
      })
    },
    uploadFileItem(id, file) {
      return new Promise((resolve, reject) => {
        const form = new FormData()
        form.append('file', file)
        uploadFile(id, form).then(({ success, message }) => {
          if (success) {
            resolve(success)
          } else {
            reject(message)
          }
        }, res => reject(res))
      })
    },
    uploadAppPackageFiles(appPackageId) {
      if (this.fileInfos && this.fileInfos.length > 0) {
        const arr = []
        for (let i = 0; i < this.fileInfos.length; ++i) {
          arr.push(new Promise((resolve, reject) => {
            this.saveAppPackageItem(appPackageId, this.fileInfos[i]).then(appPackageItemId => {
              this.uploadFileItem(appPackageItemId, this.fileInfos[i].file).then(success => resolve(success), message => reject(message))
            }, message => reject(message))
          }))
        }
        uploadPackageFiles(arr).then(res => {
          this.addLoading = false
          this.fileList = []
          this.$message({
            type: 'success',
            message: '上传成功！'
          })
          this.addFormVisible = false
          this.loadPageList()
        }, (message) => {
          this.addLoading = false
        })
      }
    },
    handlePackageItem(index, row) {
      this.appPackageFileVisible = true
      this.appPackageFileTitle = '应用[' + row.appName + ']的文件'
      this.loadAppPackageFiles(row.id)
    },
    loadAppPackageFiles(id) {
      this.appPackageFileListLoading = true
      appPackageFileItems(id).then(({ success, message, data }) => {
        this.appPackageFileListLoading = false
        if (success) {
          this.appPackageFileList = data || []
        } else {
          this.$message({
            message: message || '查询应用的文件失败',
            type: 'error'
          })
        }
      }, () => {
        this.appPackageFileListLoading = false
      })
    },
    handleSetLatest(index, row) {
      this.$confirm('确认设置为最新版本吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        setAppPackageLatest(row.id).then(({ success, message }) => {
          this.listLoading = false
          if (success) {
            this.$message({
              message: message || '设置成功',
              type: 'success'
            })
            this.loadPageList()
          } else {
            this.$message({
              message: message || '设置失败',
              type: 'error'
            })
          }
        }, (res) => {
          this.listLoading = false
        })
      }).catch(() => {

      })
    },
    handleDownloadZip(index, row) {
      this.$confirm('是否确认下载程序包?', '提示', {
        type: 'warning'
      }).then(() => {
        row.loading = true
        downloadAppPackage(row.id).then(res => {
          row.loading = false
          const fileName = util.http.parseFilename(res) || 'app.zip'
          util.downloader.downloadBlob(res.data, fileName)
        }, (res) => {
          row.loading = false
        })
      })
    },
    handleDownloadQrCode(index, row) {
      this.qrCodeVisible = true
      this.qrInfo.name = this.formatAppName(row)
      this.qrInfo.version = row.versionName
      this.qrContent = window.location.origin + process.env.VUE_APP_BASE_API + '/movieserver/appPackages/' + row.id + '/zip'
    },
    handleDeletePackage(index, row) {
      this.$confirm('确认删除记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        deleteAppPackage(row.id).then(({ success, message }) => {
          this.listLoading = false
          if (success) {
            this.$message({
              message: message || '删除成功',
              type: 'success'
            })
            this.loadPageList()
          } else {
            this.$message({
              message: message || '删除失败',
              type: 'error'
            })
          }
        }, (res) => {
          this.listLoading = false
        })
      }).catch(() => {

      })
    }
  }
}
</script>

<style lang="scss" scoped>
.qr-code-container {
  text-align: center;
  img {
    display: inline-block;
  }
}
</style>
